package com.zhixing.service.parse;

import com.zhixing.common.ISwaggerConstants;
import com.zhixing.model.SwaggerAPI;
import com.zhixing.model.SwaggerDefinitionModelAttr;
import com.zhixing.service.processor.SwaggerRequestProcessor;
import com.zhixing.service.processor.SwaggerResponseCodeProcessor;
import com.zhixing.service.processor.SwaggerResponseModelAttrsProcessor;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

import static com.zhixing.common.IConstants.SUCCESS_CODE;

/**
 * Swagger paths 标签解析器 (可选导出)
 * <p> 解析 Swagger 中 paths 字段内容，该字段内容为所有API 请求数据内容 </p>
 * <p> 该数据包含了返回结果集对象和入参对象，依赖于 definition 标签的解析 </p>
 *
 * @see {@link SwaggerDefinitionsDefinitionsParser}
 * @author zhixing
 */
public class OptionalSwaggerPathParser implements SwaggerParser{

    /** api 组装表格数据 解析返回结果 **/
    @Getter
    private List<SwaggerAPI>                            resultTableList;

    /** swagger json 解析后的所有 map数据 **/
    @Getter
    private Map<String, Object>                         allMap;

    /** definitions 解析后的标签数据，包含了所有对象数据 **/
    private Map<String, SwaggerDefinitionModelAttr>     definitionMap;

    /** 参与文档生成的 tags 标签 **/
    private List<String>                                includeTags;

    private OptionalSwaggerPathParser(){
        this.resultTableList = new ArrayList<>();
        this.includeTags = new ArrayList<>();
    }

    public static OptionalSwaggerPathParser.Builder createBuild(){
        return  new OptionalSwaggerPathParser.Builder();
    }

    public static class Builder{
        private OptionalSwaggerPathParser parser;

        public Builder(){
            this.parser = new OptionalSwaggerPathParser();
        }

        public OptionalSwaggerPathParser.Builder definitinMap(Map<String, SwaggerDefinitionModelAttr> definitinMap){
            this.parser.definitionMap = definitinMap;
            return this;
        }

        public OptionalSwaggerPathParser.Builder allMap(Map<String, Object> allMap){
            this.parser.allMap = allMap;
            return this;
        }

        public OptionalSwaggerPathParser.Builder includeTags(List<String > includeTags){
            this.parser.includeTags = includeTags;
            return this;
        }

        public OptionalSwaggerPathParser build(){
            return this.parser;
        }

    }

    @Override
    public OptionalSwaggerPathParser parse() throws IOException {
        doParse();
        return this;
    }

    private void doParse() throws IOException {
        Map<String, Map<String, Object>> paths = (Map<String, Map<String, Object>>) allMap.get(ISwaggerConstants.PATHS);
        if (paths != null) {
            Iterator<Map.Entry<String, Map<String, Object>>> it = paths.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Map<String, Object>> path = it.next();

                Iterator<Map.Entry<String, Object>> it2 = path.getValue().entrySet().iterator();
                // API 路径
                String url = path.getKey();

                // 获取 API 下的相关参数内容
                while (it2.hasNext()) {
                    Map.Entry<String, Object> request = it2.next();
                    // 获取请求方式，如： get,post,delete,put
                    String requestType = request.getKey();

                    Map<String, Object> content = (Map<String, Object>) request.getValue();

                    // class 说明，如：tags 标识
                    String title = String.valueOf(((List) content.get(ISwaggerConstants.IPATHS.TAGS)).get(0));
                    if(!CollectionUtils.isEmpty(includeTags)){
                        if(!includeTags.contains(title)){
                            continue;
                        }
                    }
                    // 方法说明
                    String tag = String.valueOf(content.get(ISwaggerConstants.IPATHS.SUMMARY));

                    // 方法说明
                    String description = String.valueOf(content.get(ISwaggerConstants.IPATHS.SUMMARY));

                    // 入参格式，如： multipart/form-data
                    String requestForm = "";
                    List<String> consumes = (List) content.get(ISwaggerConstants.IPATHS.CONSUMER);
                    if (consumes != null && consumes.size() > 0) {
                        requestForm = StringUtils.join(consumes, ",");
                    }

                    // 返回参数格式，如： application/json
                    String responseForm = "";
                    List<String> produces = (List) content.get(ISwaggerConstants.IPATHS.PRODUCES);
                    if (produces != null && produces.size() > 0) {
                        responseForm = StringUtils.join(produces, ",");
                    }

                    // 请求参数
                    List<LinkedHashMap> parameters = (ArrayList) content.get(ISwaggerConstants.IPATHS.PARAMETERS);

                    // 返回数据
                    Map<String, Object> responses = (LinkedHashMap) content.get(ISwaggerConstants.IPATHS.RESPONSES);

                    // 封装 API 对象
                    SwaggerAPI swaggerApi = new SwaggerAPI();

                    swaggerApi.setTitle(title);
                    swaggerApi.setUrl(url);
                    swaggerApi.setTag(tag);
                    swaggerApi.setDescription(description);
                    swaggerApi.setRequestForm(requestForm);
                    swaggerApi.setResponseForm(responseForm);
                    swaggerApi.setRequestType(requestType);
                    swaggerApi.setRequestList(SwaggerRequestProcessor.createBuild()
                            .parameters(parameters)
                            .definitinMap(definitionMap)
                            .build()
                            .process()
                            .getResultList());
                    swaggerApi.setResponseList(SwaggerResponseCodeProcessor.createBuild()
                            .responses(responses)
                            .build()
                            .process()
                            .getResultList());

                    // 取出来状态是200时的返回值
                    Map<String, Object> obj = (Map<String, Object>) responses.get(SUCCESS_CODE);
                    if (obj != null && obj.get(ISwaggerConstants.IPATHS.SCHEMA) != null) {
                        swaggerApi.setModelAttr(SwaggerResponseModelAttrsProcessor.createBuild()
                                .responseObj(obj)
                                .definitinMap(definitionMap)
                                .build()
                                .process()
                                .getResult());
                    }

                    /*//示例
                    table.setRequestParam(SwaggerRequestParamProcessor.createBuild()
                            .requestList(table.getRequestList())
                            .build()
                            .process()
                            .getResultStr()
                            .toString()
                    );
                    table.setResponseParam(SwaggerResponseProcessor.createBuild()
                            .responseObj(obj)
                            .definitinMap(definitionMap)
                            .build()
                            .process()
                            .getResultStr());*/

                    resultTableList.add(swaggerApi);
                }
            }
        }
    }
}
